package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
/**
 * 菜品的管理
 */
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;



    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");

    }

    /**
     * 菜品管理的分页查询，起初菜品分类没显示只有显示菜品id
     * 这个步骤不理解，菜品分类未显示
     * 在dishdto操作数据显示
     * 知道对应的id去查找对应的名称 页面给的是categoryId，需要的是categoryName  dish.category_id=category.id->category.name
     * 思路：1、先把Dish的内容全部查询出来，里面会给出categoryId,因为dishDto设置了categoryName,就把查出来的name赋值到dishDto的categoryName上
     *      2、把分页信息的record的内容单独拎出来,去设置record的categoryName
     *      3、record的内容用stream.map设置内容
     *        3.1 把record的值拷贝到item里
     *        3.2 然后通过获取record(dish表)的categoryId的值去Category表里查询，因为record里的id(dish.categoryId=category.id)
     *        3.2 查询到对应内容后获取他的categoryName
     *        3.3 设置dishDto的categoryName
     *      4、然后把设置完的DishDto的值设置到dishDtoPage.record的分页内容里
     */

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);  //模糊查询
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo, queryWrapper);
        //对象拷贝，把pageinfo的信息拷贝到dishDtoPage,除了records，因为是个list集合存放的是dish的内容
        //最后返回dishDtoPage内容，把record拎出来
        BeanUtils.copyProperties(pageInfo, dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        //把dishDto的record值通过id查询设置categoryName的值
        List<DishDto> list= records.stream().map((item)->{
            DishDto dishDto = new DishDto();  //创建新的对象
            //拷贝分页对象，内容都有除了类别名称没有，这时就需要根据id查询出分类名称了
            BeanUtils.copyProperties(item, dishDto);
            //item.getCategoryId是dish的id，因为dishDto继承了dish表和dish_flavor表，所以dish的id可以根据传入的id去category表里查对应的id
            Long categoryId = item.getCategoryId();//菜品分类id
            //根据id查询分页对象
            Category category = categoryService.getById(categoryId);
            //通过根据id查询出来的菜品内容获取它对应的名称
            String name1 = category.getName();
            //把获取到的菜品名赋值给新建对象的dto
            dishDto.setCategoryName(name1);
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);//把Dish的内容赋值到list返回给DishDto
        return R.success(dishDtoPage);
    }

    /**
     * 修改菜品时需要先回显，前面的save方法已经回显菜品分类的信息了
     *
     */

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }


    /**
     * 修改点击保存菜品
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("新增菜品成功");

    }


    /**
     * 菜品管理删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("删除的id为{}",ids);
        dishService.removeWithDishFlavors(ids);
        return R.success("删除成功");
    }


//    /**
//     * 新增套套餐时
//     * 根据菜品分类查询对应的菜品数据并添加到菜品窗口
//     */
//    @GetMapping("/list")
//   public R<List<Dish>> list(Dish dish) {
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        // 1为售卖状态
//        queryWrapper.eq(Dish ::getStatus,1);
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//   }

    /**
     * 前端展示需要用到DishDto
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        // 1为售卖状态
        queryWrapper.eq(Dish ::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        List<DishDto> collect = list.stream().map(
                (item) -> {
                    DishDto dishDto = new DishDto();
                    BeanUtils.copyProperties(item, dishDto);
                    Long categoryId = item.getCategoryId();
                    Category serviceById = categoryService.getById(categoryId);
                    if (serviceById != null) {
                        String name = serviceById.getName();
                        dishDto.setName(name);
                    }
                    LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(DishFlavor::getDishId, item.getId());
                    List<DishFlavor> list1 = dishFlavorService.list(lambdaQueryWrapper);
                    dishDto.setFlavors(list1);
                    return dishDto;
                }).collect(Collectors.toList());
        return R.success(collect);
    }

}
